package org.vectrics.company.web.struts;

import javax.servlet.jsp.JspException;

import org.apache.log4j.Category;
import org.vectrics.NoProviderException;
import org.vectrics.company.Company;
import org.vectrics.hibernate.ThreadProperties;
import org.vectrics.history.HistoryProvider;
import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.struts.VectricsActionData;
import org.vectrics.struts.VectricsStrutsAction;
import org.vectrics.user.Person;


public class CompanyRemoveAction extends VectricsStrutsAction {
    private static Category log = Category.getInstance(CompanyRemoveAction.class);
	public static String JOB_PARAM = "job";


	@Override
	protected String doExecute(VectricsActionData actionData) throws JspException {
		try {
			log.debug("execute() - called");
			Person authPerson = CoreServiceLocator.getUserAuthService().getAuthorizedPerson(ThreadProperties.getDomain(), actionData.getRequest());
				 	
			CompanyForm form = null;			
			CompanyForm companyForm = null;
			if (actionData.getForm() == null) {
				companyForm = new CompanyForm();
				form = companyForm;			
			}
			else {
				companyForm = (CompanyForm)form;
			}
			if ("request".equals(actionData.getMapping().getScope())) {
				actionData.getRequest().setAttribute(actionData.getMapping().getAttribute(), companyForm);
			}
			else {
				actionData.getRequest().setSessionAttribute(actionData.getMapping().getAttribute(), companyForm);
			}
			
			String companyId = actionData.getRequest().getParameter("companyId");		
			
			try {
				
				Company company = CoreServiceLocator.getCompanyService().findCompany(new Long(companyId));
				if (company != null) {
					if (company.getVoided() == false) {
						log.debug("execute() - deactivating company");
						company.setVoided(true);
						HistoryProvider.getInstance().createHistory(Company.OBJECT_TYPE, 
								company.getId().toString(), "company_void", 
								authPerson, 
								"Voided company: " + company.getName());
					} 
				}
				CoreServiceLocator.getCompanyService().updateCompany(company);
			}
			catch (Exception ex) {
				log.error("Exception finding company", ex);
				throw new JspException("Exception finding company", ex);
			}
			saveToken(actionData.getRequest().getHttpRequest());
		}
		catch (NoProviderException ne) {
			log.error("No provider exception", ne);
			throw new JspException("No provider exception", ne);
		}
		log.debug("execute() - finished");
		
		return ("success");
	}
}
